import base64
import json
import pickle

from django.http import HttpResponseForbidden, JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from carts import constants
from goods.models import SKU
from meiduo_mall.utils.response_code import RETCODE

class CartSimpleview(View):
    """商品页面右上角购物车"""

    def get(self,request):
        # 判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # redis
            redis_conn = get_redis_connection('carts')
            redis_cart = redis_conn.hgetall('carts_%s' % user.id)
            cart_selected = redis_conn.smembers('selected_%s' % user.id)
            cart_dict = {}
            for sku_id,count in redis_cart.items():
                cart_dict[int(sku_id)] = {
                    'count':int(count),
                    'selected':sku_id in cart_selected
                }

        else:
            # cookies
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}
        # 组织响应数据
        cart_skus = []
        sku_ids = cart_dict.keys()
        skus = SKU.objects.filter(id__in = sku_ids)
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': cart_dict[sku.id]['count'],
                'default_image': sku.default_image.url,
            })
        return JsonResponse({'code':RETCODE.OK,'errmsg':'OK','cart_skus':cart_skus})


class CartsSelectAllView(View):
    """全选购物车"""

    def put(self,request):
        json_dict = json.loads(request.body.decode())
        selected = json_dict.get('selected', True)
        if selected:
            if not isinstance(selected, bool):
                return HttpResponseForbidden('参数selected有误')
        # 用户是否登录
        user = request.user
        if user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            cart = redis_conn.hgetall('carts_%s'% user.id)
            sku_id_list = cart.keys()
            if selected:
                #　全选
                redis_conn.sadd('selected_%s' % user.id,*sku_id_list)
            else:
                # 取消全选
                redis_conn.srem('selected_%s' % user.id,*sku_id_list)
            # 响应
            return JsonResponse({'code': RETCODE.OK, 'errmsg': '全选购物车成功'})
        else:
            # cookies
            # cookies
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
                for sku_id in cart_dict:
                    cart_dict[sku_id]['selected'] = selected
            else:
                cart_dict = {}

            # 将字典转成base64的bytes格式
            cookies_cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()
            response = JsonResponse({'code': RETCODE.OK, 'errmsg': '全选购物车成功'})
            response.set_cookie('carts', cookies_cart_str, max_age=constants.CARTS_COOKIES_EXPIRES)
            return response


class CartsView(View):
    """购物车管理"""

    def delete(self,request):
        """删除购物车数据"""
        # 接受参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return HttpResponseForbidden('商品不存在')
            # 用户是否登录
        user = request.user
        if user.is_authenticated:
            # redis
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()
            # 删除指定的键
            pl.hdel('carts_%s' % user.id, sku_id)
            pl.srem('selected_%s' % user.id,sku_id)
            pl.execute()
            # 删除不需要返回数据,让前端局部刷新就好
            return JsonResponse({'code':RETCODE.OK,'errmsg':'删除购物车成功'})

        else:
            # cookies
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}
            del cart_dict[sku_id]
            # 将字典转成base64的bytes格式
            cookies_cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()
            # 组织响应 让前端局部刷新
            response = JsonResponse({'code': RETCODE.OK, 'errmsg': '删除购物车成功'})
            response.set_cookie('carts', cookies_cart_str, max_age=constants.CARTS_COOKIES_EXPIRES)
            return response



    def put(self,request):
        """修改购物车"""
        # 接受参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected',True)

        # 校验
        if not all([sku_id,count]):
            return HttpResponseForbidden('缺少参数')
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return HttpResponseForbidden('商品不存在')
        try:
            count = int(count)
        except Exception:
            return HttpResponseForbidden('参数count有误')
        if selected:
            if not isinstance(selected, bool):
                return HttpResponseForbidden('参数selected有误')
        # 用户是否登录
        user = request.user
        if user.is_authenticated:
            # redis
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()
            # 接口是幂等的，直接覆盖就好,没有会新建，有会更新
            pl.hset('carts_%s' % user.id, sku_id, count)
            # 是否选中
            if selected:
                pl.sadd('selected_%s' % user.id,sku_id)
            else:
                pl.srem('selected_%s' % user.id,sku_id)
            # 执行
            pl.execute()
            # 组织响应
            cart_sku = {
                'id':sku_id,
                'name':sku.name,
                'count':count,
                'selected':selected,
                'default_image':sku.default_image.url,
                'price':sku.price,
                'amount':sku.price * count,

            }
            return JsonResponse({'code':RETCODE.OK,'errmsg':'修改购物车成功','cart_sku':cart_sku})
        else:
            # cookies
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}
            cart_dict[sku_id] = {
                'count':count,
                'selected':selected
            }
            # 将字典转成base64的bytes格式
            cookies_cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()
            # 组织响应
            cart_sku = {
                'id': sku_id,
                'name': sku.name,
                'count': count,
                'selected': selected,
                'default_image': sku.default_image.url,
                'price': sku.price,
                'amount': sku.price * count,

            }
            response = JsonResponse({'code': RETCODE.OK, 'errmsg': '修改购物车成功', 'cart_sku': cart_sku})
            response.set_cookie('carts',cookies_cart_str,max_age=constants.CARTS_COOKIES_EXPIRES)
            return response


    def get(self,request):
        """提供购物车展示页面"""
        user = request.user
        if user.is_authenticated:
            # redis
            redis_conn = get_redis_connection('carts')
            redis_carts = redis_conn.hgetall('carts_%s'%user.id)
            carts_selected = redis_conn.smembers('selected_%s' % user.id)

            # 组织数据
            cart_dict = {}
            for sku_id,count in redis_carts.items():
                cart_dict[int(sku_id)] = {
                    'count':int(count),
                    'selected':sku_id in carts_selected,
                }
            pass
        else:
            # cookies
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}
        # 渲染购物车信息
        sku_ids = cart_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        cart_skus = []
        for sku in skus:
            cart_skus.append({
                'id':sku.id,
                'name':sku.name,
                'count':cart_dict.get(sku.id).get('count'),
                'selected':str(cart_dict[sku.id]['selected']),
                'default_image':sku.default_image.url,
                'price':str(sku.price),
                'amount':str(float(sku.price) * int(cart_dict[sku.id]['count'])),
            })

        context = {
            'cart_skus': cart_skus,
        }

        # 渲染购物车页面
        return render(request, 'cart.html', context)


    def post(self,request):
        """添加购物车"""
        # 接受参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected',True)

        # 校验参数
        if not all([sku_id,count]):
            return HttpResponseForbidden('缺少必要参数')
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return HttpResponseForbidden('商品不存在')
        try:
            count = int(count)
        except Exception:
            return HttpResponseForbidden('参数count有误')
        if selected:
            if not isinstance(selected,bool):
                return HttpResponseForbidden('参数selected有误')
        # 用户是否登录
        user = request.user
        if user.is_authenticated:
            # redis
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()
            # 直接使用步长添加
            pl.hincrby('carts_%s'%user.id,sku_id,count)
            pl.sadd('selected_%s' % user.id,sku_id)
            pl.execute()
            # 响应
            return JsonResponse({'code':RETCODE.OK,'errmsg':'添加购物车成功'})
        else:
            # cookies
            cart_str = request.COOKIES.get('carts')
            # 如果用户操作过，将bytes转成 base64的bytes，再将 bytes转成字典
            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}
            if sku_id in cart_dict:
                # 累加
                origin_count = cart_dict[sku_id]['count']
                count += origin_count
                cart_dict[sku_id] = {
                    'count':count,
                    'selected':selected,
                }
            cart_dict[sku_id] = {'count':count,'selected':selected}
            # 将字典转成base64的bytes格式
            cookies_cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()
            # 创建响应对象
            response = JsonResponse({'code':RETCODE.OK,'errmsg':'添加购物车成功'})
            response.set_cookie('carts',cookies_cart_str,max_age=constants.CARTS_COOKIES_EXPIRES)
            return response
